﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ODP.Helper;
using System.Net.Json;
using ODP.Model;
using ODP.Com;
using ODP.Enum;

namespace ODP.SinaCrawler
{
    public partial class MainForm : Form
    {
        #region 属性
        private int m_appKeyIndex;

        public int AppKeyIndex
        {
            get
            {
                if (ODP.Com.Current.OAuth != null)
                {
                    m_appKeyIndex = ODP.Com.Current.AppKeyIndex;
                }
                else
                {
                    m_appKeyIndex = 1;
                }
                return m_appKeyIndex;
            }
            set { m_appKeyIndex = value; }
        }

        private string m_AppKey;

        public string AppKey
        {
            get { return Helper.GetAppKey(AppKeyIndex); }
            set { m_AppKey = value; }
        }
        private string m_AppSecret;

        public string AppSecret
        {
            get { return Helper.GetAppSecret(AppKeyIndex); }
            set { m_AppSecret = value; }
        }

        private IDictionary<string, bool> m_Users = new Dictionary<string, bool>();

        public IDictionary<string, bool> Users
        {
            get { return m_Users; }
            set { m_Users = value; }
        }

        private IList<CheckBoxListItem> cbliList = new List<CheckBoxListItem>();

        private DateTime m_beginDateTime;

        private DateTime m_currentUserBeginDateTime;

        private bool m_pause = false;

        public bool Pause
        {
            get { return m_pause; }
            set { m_pause = value; }
        }
        #endregion


        public MainForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            backgroundWorker1.WorkerReportsProgress = true;
            new InitHelper().InitCheckBoxListItem(ref cbliList);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            CheckLogon();

            Current.MainForm = this;
        }

        public void CheckLogon()
        {
            if (!Current.IsLogon)
            {
                //
                Login l = new Login();

                if (l.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    SinaAPI.SinaAPI qqAPI = new SinaAPI.SinaAPI();

                    string result = qqAPI.GetCurrentUserInfo(ODP.Com.Current.OAuth, ODP.Com.Current.OAuth.twitterType, new QueryStringParameter("uid", ODP.Com.Current.OAuth.Uid));

                    SetCurrentUserInfoToControl(result);

                    //获取系统推荐的用户
                    GetMayKownPerson();

                    //获取热门用户
                    GetHotPerson();

                    //根据内容获取推荐用户
                    GetMayKownPersonByContent();

                    BindCatalog();

                    lbwaitSearch.Text = "待搜索用户数:" + Users.Count.ToString();
                }
                else
                {
                    this.Close();
                    Application.Exit();
                }
            }
        }

        private void GetMayKownPersonByContent()
        {
            SinaAPI.SinaAPI qqAPI = new SinaAPI.SinaAPI();
            string result = qqAPI.GetHotPerson(ODP.Com.Current.OAuth, ODP.Com.Current.OAuth.twitterType);

            JsonTextParser jtp = new JsonTextParser();

            if (!string.IsNullOrEmpty(result))
            {
                IList<ODP.Model.HotInfo> hiList = JsonHelper.GetJsonObeject<List<ODP.Model.HotInfo>>(result);

                foreach (HotInfo hi in hiList)
                {
                    if (!Users.ContainsKey(hi.id.ToString()))
                    {
                        Users.Add(hi.id.ToString(), false);
                    }
                }
            }
        }

        private void GetHotPerson()
        {
            SinaAPI.SinaAPI qqAPI = new SinaAPI.SinaAPI();
            string result = qqAPI.GetHotPerson(ODP.Com.Current.OAuth, ODP.Com.Current.OAuth.twitterType, new QueryStringParameter("category", "default"));

            if (!string.IsNullOrEmpty(result))
            {
                IList<ODP.Model.HotInfo> hiList = JsonHelper.GetJsonObeject<List<ODP.Model.HotInfo>>(result);

                foreach (HotInfo hi in hiList)
                {
                    if (!Users.ContainsKey(hi.id.ToString()))
                    {
                        Users.Add(hi.id.ToString(), false);
                    }
                }

            }
        }

        private void GetMayKownPerson()
        {
            SinaAPI.SinaAPI qqAPI = new SinaAPI.SinaAPI();
            string result = qqAPI.GetMayKownPerson(ODP.Com.Current.OAuth, ODP.Com.Current.OAuth.twitterType);

            JsonTextParser jtp = new JsonTextParser();

            if (!string.IsNullOrEmpty(result))
            {
                JsonArrayCollection jac = jtp.Parse(result) as JsonArrayCollection;
                if (jac != null && jac.Count > 0)
                {
                    foreach (JsonObjectCollection item in jac)
                    {
                        JsonObjectCollection tempItem = item[1] as JsonObjectCollection;

                        foreach (JsonObjectCollection temp in tempItem)
                        {
                            JsonArrayCollection jocResult = temp["uid"] as JsonArrayCollection;

                            foreach (JsonObject jo in jocResult)
                            {
                                if (!Users.ContainsKey(Convert.ToString(jo.GetValue())))
                                {
                                    Users.Add(Convert.ToString(jo.GetValue()), false);
                                }
                            }
                        }

                    }
                }
            }
        }

        private void SetCurrentUserInfoToControl(string result)
        {
            this.lbfansnum.Text += JsonHelper.GetValueByName(result, "followers_count");
            this.lbidolnum.Text += JsonHelper.GetValueByName(result, "friends_count");
            this.lbisvip.Text += JsonHelper.GetValueByName(result, "verified");
            this.lblocation.Text += JsonHelper.GetValueByName(result, "location");

            this.lbnick.Text += JsonHelper.GetValueByName(result, "screen_name");
            this.lbsex.Text += JsonHelper.GetValueByName(result, "gender") == "m" ? "男" : "女";
            this.lbtweetnum.Text += JsonHelper.GetValueByName(result, "statuses_count");
            this.lbuserid.Text += JsonHelper.GetValueByName(result, "name");
            this.lbsismyidol.Text += JsonHelper.GetValueByName(result, "verifyinfo");
            this.lbCreateDate.Text += JsonHelper.GetValueByName(result, "created_at");
        }

        private void cbAutoStop_CheckedChanged(object sender, EventArgs e)
        {

        }

        #region 多线处理用户信息
        /// <summary>
        /// 多线处理用户信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            if (!Pause)
            {
                string result = "";
                SinaAPI.SinaAPI qqAPI = new SinaAPI.SinaAPI();
                var items = Users.Where(p => !p.Value).ToDictionary(p => p.Key, p => p.Value);

                int i = 0;

                QueryStringParameter qspnames = new QueryStringParameter("uid", "");

                if (items.Count > 0)
                {
                    #region 对用户进行一些相关操作

                    foreach (var item in items)
                    {
                        
                            QueryStringParameter qsp = new QueryStringParameter("uid", item.Key);

                            qspnames.Value += item.Key + ",";

                            //获取到用户信息
                            result = qqAPI.GetOtherUserInfo(ODP.Com.Current.OAuth, ODP.Com.Current.OAuth.twitterType, qsp);

                            //显示当前用户信息
                            ODP.Model.UserInfo ui = JsonHelper.GetJsonObeject<ODP.Model.UserInfo>(result);

                            SetSearchUserInfoToControl(ui);

                            //动作
                            #region 进行各项互动动作

                            #region 登陆用户没有关注当前的搜索用户时,进行各项友好示意
                            if (!ui.follow_me)
                            {
                                #region 添加收听
                                if (cbaddfans.Checked)
                                {
                                    try
                                    {
                                        result = qqAPI.AddFriends(ODP.Com.Current.OAuth, ODP.Com.Current.OAuth.twitterType, qsp);
                                        System.Threading.Thread.Sleep(1000 * 10);
                                    }
                                    catch (Exception ee)
                                    {
                                        Users[item.Key] = true;
                                        i++;
                                        backgroundWorker1.ReportProgress(i);
                                        if (ee.Message.Contains("502"))
                                        {
                                            Current.IsLogon = false;
                                            Current.OAuth.tokenKey = "";
                                            Helper.SetAppKeyIndex(Current.AppKeyIndex);
                                            CheckLogon();
                                        }
                                    }
                                }
                                #endregion

                                #region 评论
                                //评论用户的第一条微博
                                if (cbComment.Checked && ui.status != null)
                                {
                                    try
                                    {
                                        QueryStringParameter comment = new QueryStringParameter("comment", string.Format("@轩轩的小巢 @{0} 转发评论是一种美德,关爱社会关爱新浪!也请您关注我!谢谢! ",ui.screen_name));
                                        QueryStringParameter id = new QueryStringParameter("id", ui.status.id.ToString());
                                        QueryStringParameter comment_ori = new QueryStringParameter("comment_ori", "1");

                                        result = qqAPI.AddComment(ODP.Com.Current.OAuth, ODP.Com.Current.OAuth.twitterType, comment, id, comment_ori);
                                        System.Threading.Thread.Sleep(1000 * 10);
                                    }
                                    catch (Exception ee)
                                    {
                                        Users[item.Key] = true;
                                        i++;
                                        backgroundWorker1.ReportProgress(i);
                                        if (ee.Message.Contains("502"))
                                        {
                                            Current.IsLogon = false;
                                            Current.OAuth.tokenKey = "";
                                            Helper.SetAppKeyIndex(Current.AppKeyIndex);
                                            CheckLogon();
                                        }
                                    }
                                }
                                #endregion

                                #region 转发
                                //转发当前用户的第一条微博
                                if (cbRepost.Checked && ui.status != null)
                                {
                                    try
                                    {
                                        QueryStringParameter id = new QueryStringParameter("id", ui.status.id.ToString());
                                        QueryStringParameter status = new QueryStringParameter("status", ui.status.text);
                                        QueryStringParameter is_comment = new QueryStringParameter("is_comment", "3");
                                        result = qqAPI.RePost(ODP.Com.Current.OAuth, ODP.Com.Current.OAuth.twitterType, status, id);
                                        System.Threading.Thread.Sleep(1000 * 10);
                                    }
                                    catch (Exception ee)
                                    {
                                        Users[item.Key] = true;
                                        i++;
                                        backgroundWorker1.ReportProgress(i);
                                        if (ee.Message.Contains("502"))
                                        {
                                            Current.IsLogon = false;
                                            Current.OAuth.tokenKey = "";
                                            Helper.SetAppKeyIndex(Current.AppKeyIndex);
                                            CheckLogon();
                                        }
                                    }
                                }
                                #endregion
                            }
                            #endregion

                            if (1 == 2)
                            {
                                #region 相关信息写如数据库
                                #region 记录当前登陆用户的信息
                                ODP.DAL.User udal = new DAL.User();
                                if (!DALHelper.Exists(FormName.user, string.Format(" id='{0}'", ui.id)).IsSuccessed)
                                {
                                    udal.AddUserInfo(ui);
                                }
                                else
                                {
                                    udal.UpdateUserInfo(ui);
                                }
                                #endregion

                                #region 记录当前用户的微博信息
                                //记录用户的微博信息
                                if (ui.status != null)
                                {
                                    ODP.DAL.Statuses status = new DAL.Statuses();
                                    if (!DALHelper.Exists(FormName.statuses, string.Format(" id='{0}'", ui.status.id)).IsSuccessed)
                                    {
                                        status.AddStatusesInfo(ui.status);
                                    }
                                }
                                #endregion

                                #region 记录当前搜索用户与当前登陆用户的关系
                                //当前搜索用户是否已经关注了当前的登陆用户
                                if (ui.follow_me)
                                {
                                    if (!DALHelper.Exists(FormName.follower, string.Format(" uid='{0}' and followerid='{1}'", Current.OAuth.Uid, ui.id)).IsSuccessed)
                                    {
                                        FollowerInfo fi = new FollowerInfo();
                                        fi.createtime = DateTime.Now;
                                        fi.uid = Convert.ToInt64(Current.OAuth.Uid);
                                        fi.followerid = Convert.ToInt64(item.Key);
                                        udal.AddFollowerInfo(fi);
                                    }
                                }

                                //当前登陆用户是否已经关注了当前的搜索用户
                                if (ui.following)
                                {
                                    if (!DALHelper.Exists(FormName.follower, string.Format(" uid='{0}' and followerid='{1}'", ui.id, Current.OAuth.Uid)).IsSuccessed)
                                    {
                                        FollowerInfo fi = new FollowerInfo();
                                        fi.createtime = DateTime.Now;
                                        fi.followerid = Convert.ToInt64(Current.OAuth.Uid);
                                        fi.uid = Convert.ToInt64(item.Key);
                                        udal.AddFollowerInfo(fi);
                                    }
                                }
                                #endregion
                                #endregion
                            }
                            #endregion

                            //标记为已爬虫
                            Users[item.Key] = true;

                            i++;
                            backgroundWorker1.ReportProgress(i);
                       
                    }

                    #endregion
                }
                else
                {
                    //获取系统推荐的用户
                    GetMayKownPerson();

                    //获取热门用户
                    GetHotPerson();

                    //根据内容获取推荐用户
                    GetMayKownPersonByContent();

                    if (Users.Count == 0)
                    {
                        Pause = true;
                    }
                }
            }
        }

        private void SetSearchUserInfoToControl(ODP.Model.UserInfo ui)
        {

            

            this.lbsfansnum.Text = "粉丝数：" + ui.followers_count;
            this.lbsidolnum.Text = "关注人数：" + ui.friends_count;
            this.lbsisvip.Text = "是否认证用户：" + ui.verified;
            this.lbslocation.Text = "所在地：" + ui.location;

            this.lbsnick.Text = "昵称：" + ui.screen_name;
            this.lbssex.Text = "性别：" + (ui.gender == "m" ? "男" : "女");
            this.lbstweetnum.Text = "已发微博数：" + ui.statuses_count;
            this.lbsuserid.Text = "用户ID：" + ui.name;
            this.lbsismyidol.Text = "是否为当前登陆用户粉丝：" + ui.follow_me;
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int hasSearchcount = Users.Where(p => p.Value).Count();
            lbhasSearch.Text = "已搜索用户数：" + hasSearchcount.ToString();
            lbwaitSearch.Text = "待搜索用户数：" + (Users.Count - hasSearchcount).ToString();
            allusedTime.Text = "所有用户已耗时：" + DateTime.Now.Subtract(m_beginDateTime).TotalSeconds;
            currentUsedTime.Text = "当前用户已耗时：" + DateTime.Now.Subtract(m_currentUserBeginDateTime).TotalSeconds;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            while (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();

                if (Pause)
                {
                    break;
                }
            }
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            if (m_beginDateTime != null)
            {
                m_beginDateTime = DateTime.Now;
            }
            if (m_currentUserBeginDateTime != null)
            {
                m_currentUserBeginDateTime = DateTime.Now;
            }
            Pause = false;

            while (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();

                if (Pause)
                {
                    break;
                }
            }
        }

        private void BindCatalog()
        {
            foreach (CheckBoxListItem cbli in cbliList)
            {
                clbCatalog.Items.Add(cbli.Text);
            }
        }

        /// <summary>
        /// 记录登陆口令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            while (!backgroundWorker2.IsBusy)
            {
                backgroundWorker2.RunWorkerAsync();
            }
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            //请求并记录一次OAuth2.0的AccessToken
            string requestString = "";
            string request_Url = "";

            List<QueryStringParameter> parameters = new List<QueryStringParameter>();

            parameters.Add(new QueryStringParameter("client_id", Current.OAuth.customKey));
            parameters.Add(new QueryStringParameter("client_secret", Current.OAuth.customSecret));
            parameters.Add(new QueryStringParameter("grant_type", "refresh_token"));
            parameters.Add(new QueryStringParameter("refresh_token", Current.OAuth.tokenKey));

            Current.OAuth.GetOauthUrl(Current.OAuth.Access_token_url, HttpMethod.POST.ToString(), parameters, out requestString, out request_Url);
            string result = new SyncHttp().HttpPost(request_Url, requestString);


            Current.OAuth.tokenKey = ODP.Helper.JsonHelper.GetValueByName(result, "access_token");
            Current.OAuth.Uid = ODP.Helper.JsonHelper.GetValueByName(result, "uid");

            OAuthInfo oainfo = new OAuthInfo();
            oainfo.accesstoken = Current.OAuth.tokenKey;
            oainfo.uid = Convert.ToInt64(Current.OAuth.Uid);
            oainfo.code = Current.OAuth.verify;
            oainfo.createtime = DateTime.Now;
            
            new DAL.OAuth().AddOAuthInfo(oainfo);

            //等待半小时
            System.Threading.Thread.Sleep(1000 * 60);
            //System.Threading.Thread.Sleep(1000 * 60 * 30);
        }

        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            while (!backgroundWorker2.IsBusy)
            {
                backgroundWorker2.RunWorkerAsync();
            }
        }
    }
}
